import { tenantModel } from '@/models/tenant'
import TenantTable from '@/pages/Tenant/components/TenantTable'
import TenantUpdateModal from '@/pages/Tenant/components/TenantUpdateModal'
import { saveTenant, TenantUpdateDTO, TenantVO, updateTenant } from '@/services/TenantService'
import { PageContainer } from '@ant-design/pro-components'
import { ActionType } from '@ant-design/pro-table'
import { message } from 'antd'
import { observer } from 'mobx-react'
import { useRef, useState } from 'react'

const Tenant = () => {
  // 编辑操作
  const [updateModalState, setUpdateModalState] = useState(false)
  const [currentTenant, setCurrentTenant] = useState<TenantVO | undefined>()
  // 表格引用
  const tableRef = useRef<ActionType>()
  const updateEvent = async (record: TenantVO) => {
    // 打开模态框
    setCurrentTenant(record)
    setUpdateModalState(true)
  }

  const saveEvent = async () => {
    // 打开模态框
    setUpdateModalState(true)
  }
  const onUpdateModalChange = async (state: boolean) => {
    if (state) {
      tenantModel.fetchMenuTree().then()
      setUpdateModalState(state)
    } else {
      await setCurrentTenant(undefined)
      setUpdateModalState(state)
    }
  }
  // 提交修改
  const onUpdateFinish = async (formData: any) => {
    let dto: TenantUpdateDTO = JSON.parse(JSON.stringify(formData))
    // 字段处理
    dto.permId = tenantModel.selectMenuKey
    let response
    if (currentTenant) {
      response = await updateTenant(dto)
    } else {
      response = await saveTenant(dto)
    }
    if (response) {
      message.success('操作成功')
      // 刷新表格
      tableRef.current?.reload()
      return true
    }
    return false
  }

  return (
    <PageContainer title="租户">
      {/*租户表格 开始*/}
      <TenantTable tableRef={tableRef} onSave={saveEvent} onUpdate={updateEvent} />
      {/*租户表格 结束*/}

      {/*修改模态框 开始*/}
      <TenantUpdateModal
        tenant={currentTenant}
        open={updateModalState}
        onOpenChange={onUpdateModalChange}
        onFinish={onUpdateFinish}
      />
      {/*修改模态框 结束*/}
    </PageContainer>
  )
}

export default observer(Tenant)
